<?php
/**
 * 体检套餐
 *
 * User: kaikaic
 * Date: 2018/10/24
 * Time: 22:53
 */

namespace app\exam\controller;

use app\exam\model\SetModel;
use app\exam\service\MecItemService;
use app\exam\service\MecService;
use app\exam\service\MecSetService;
use controller\BasicAdmin;
use service\ConfigService;
use think\Db;

class Set extends BasicAdmin {

    protected $table = "ExamSet";

    /**
     * 体检套餐-列表
     */
    public function index() {
        $this->title = "体检套餐";

        $name = $this->request->get("name");
        $isGroup = $this->request->get("isgroup");
        $mecID = intval($this->request->get("mec_id"));
        $status = intval($this->request->get("status", 1));
        $uniqueCode = $this->request->get("unique_code");

        $query = array();
        if ($mecID) {
            $query['mec_id'] = $mecID;
        }
        if ($name) {
            $query['name'] = array('like', "%{$name}%");
        }
        if ($uniqueCode) {
            $query['unique_code'] = $uniqueCode;
        }
        if ($isGroup) {
            $query['isgroup'] = $isGroup;
        }
        if ($status) {
            $query['status'] = $status;
        }

        parent::listRecordByPage($query, "", "id desc");
    }

    /**
     * 体检套餐-新增
     */
    public function add() {
        if ($this->request->isGet()) {
            $vo = array();
            return view('form', [
                'title'=>'新增体检套餐',
                'vo'=>$vo,
                'isgroup'=>$this->request->param('isgroup'),
                'mecs'=>MecService::getInstance()->listMec(),
                'settype'=>MecService::getInstance()->getSetType(),
            ]);
        }

        if ($this->request->isPost()) {
            $isgroup = $this->request->post('isgroup', '');
            $data = $this->request->post();
            if ($this->doInsertAction($data)) {
                $this->showSuccess('添加成功！', "/exam/set/index?isgroup=".$isgroup);
            }else {
                $this->error('添加失败，请稍候再试！');
            }
        }
    }

    /**
     * 体检套餐-编辑
     */
    public function edit() {
        if ($this->request->isGet()) {
            $id = $this->request->get('id', '');
            if (empty($id)) {
                $this->error('参数错误，请稍候再试！');
            }

            $set = MecSetService::getInstance()->find($id);
            if (empty($set)) {
                $this->error('记录不存在，请重新操作!');
            }
            $set['set_type']  = explode(',',$set['set_type']);
            return view('form', [
                'title'=>'编辑体检套餐',
                'vo'=>$set,
                'isgroup'=>$this->request->param('isgroup'),
                'mecs'=>MecService::getInstance()->listMec(),
                'settype'=>MecService::getInstance()->getSetType(),
            ]);
        }

        if ($this->request->isPost()) {
            $id = $this->request->post('id', '');
            $isgroup = $this->request->post('isgroup', '');
            if (empty($id)) {
                $this->error('参数错误，请稍候再试！');
            }

            $data = $this->request->post();
            if ($this->doInsertAction($data)) {
                $this->showSuccess('编辑成功！', "/exam/set/index?isgroup=".$isgroup);
            }else {
                $this->error('编辑失败，请稍候再试！');
            }
        }
    }

    /**
     * 体检套餐-删除
     */
    public function remove() {
        $id = intval($this->request->post('id', ''));
        if (empty($id)) {
            $this->error('参数错误!');
        }

        $set = MecSetService::getInstance()->find($id);
        if (empty($set)) {
            $this->error('记录不存在，请重新操作!');
        }

        $result = MecSetService::getInstance()->remove(array('id'=>$id));
        if ($result) {
            $this->success('删除成功!', '');
        }else {
            $this->error('删除失败，请重新再试!');
        }
    }

    /**
     * 设置体检套餐-项目内容
     */
    public function item() {
        $id = intval($this->request->param('id', ''));
        if (empty($id)) {
            $this->error('参数错误!');
        }

        $set = MecSetService::getInstance()->find($id);
        if (empty($set)) {
            $this->error('记录不存在，请重新操作!');
        }

        //TODO 查询
        $itemIDs = unserialize($set['item_ids']);
        $recordList = MecItemService::getInstance()->listItemByIDs($itemIDs);

        for ($i=0; $i<count($recordList); $i++) {
            $mecID = $recordList[$i]['mec_id'];
            $itemSetID = $recordList[$i]['item_set_id'];

            $recordList[$i]['mec'] = "";
            $mec = MecService::getInstance()->find($mecID);
            if ($mec) {
                $recordList[$i]['mec'] = $mec['name'];
            }

            $recordList[$i]['item_set'] = "";
            $itemSet = MecItemService::getInstance()->single(array('id'=>$itemSetID));
            if ($itemSet) {
                $recordList[$i]['item_set'] = $itemSet['name'];
            }
        }

        return view('item', [
            'title'=>"体检项目/" . $set['name'],
            'set'=>$set,
            'list'=>$recordList,
        ]);
    }

    /**
     * 添加体检项目
     */
    public function editItem() {
        $setID = intval($this->request->param("set_id"));
        if (!$setID) {
            $this->error('参数错误!');
        }

        $set = MecSetService::getInstance()->find($setID);
        if (empty($set)) {
            $this->error('记录不存在，请重新操作!');
        }

        if ($this->request->isGet()) {
            $set['item_ids'] = unserialize($set['item_ids']);

            $items = MecItemService::getInstance()->listItemsByMec($set['mec_id']);
            for ($i=0; $i<count($items); $i++) {
                $items[$i]['items'] = array_chunk($items[$i]['items'], 3);
            }

            return view('item_edit', [
                'title'=>'编辑体检项目',
                'vo'=>$set,
                'items'=>$items
            ]);
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();

            $result = MecSetService::getInstance()->update(array('item_ids'=>serialize($data['item_ids'])), $setID);
            if ($result) {
                $this->success('添加成功！', "");
            }else {
                $this->error('添加失败，请稍候再试！');
            }
        }
    }
    public function import() {
        if ($this->request->isGet()) {
            return view('import', [
                'title'=>'导入套餐'
            ]);
        }

        if ($this->request->isPost()) {
            if ($this->doImportAction()) {
                $this->success('导入完成！', "");
            }else {
                $this->error('导入失败，请稍候再试！');
            }
        }
    }
    public function changeTabelVal() {
        $id = intval($this->request->param('id', ''));
        if (empty($id)) {
            $this->error('参数错误，请重新操作删除!');
        }
        $value = $this->request->post('value',1);
        $field = $this->request->post('field','');
        Db::name($this->table)->where('id', $id)->update(array($field=>$value));
        $this->success('操作成功!', '');
    }
    private function doImportAction() {
        $data = $this->request->post();
        $excelFile = $data['set_excel'];
        if (!$excelFile) {
            return false;
        }

        $SetModel = new SetModel();
        $SetModel->readExcelFile($excelFile);

        return true;
    }
    /**
     * 删除套餐里的体检项目
     */
//    public function removeItem() {
//        $id = intval($this->request->post('id', ''));
//        if (empty($id)) {
//            $this->error('参数错误!');
//        }
//
//        $setID = intval($this->request->param("set_id"));
//        if (!$setID) {
//            $this->error('参数错误!');
//        }
//
//        $set = MecSetService::getInstance()->find($setID);
//        if (empty($set)) {
//            $this->error('记录不存在，请重新操作!');
//        }
//
//        $itemIDs = unserialize($set['item_ids']);
//        $index = array_search($id, $itemIDs);
//        if ($index === false) {
//            $this->error('没有这个记录!');
//        }
//        array_splice($itemIDs, $index, 1);
//
//        $result = MecSetService::getInstance()->update(array('item_ids'=>serialize($itemIDs)), $setID);
//        if ($result) {
//            $this->success('删除成功!', '');
//        }else {
//            $this->error('删除失败，请重新再试!');
//        }
//    }

    /**
     * 体检套餐-复制
     */
    public function copy() {
        $id = intval($this->request->param('id', ''));
        if (empty($id)) {
            $this->error('参数错误!');
        }

        $set = MecSetService::getInstance()->find($id);
        if (empty($set)) {
            $this->error('记录不存在，请重新操作!');
        }

        unset($set['id']);
        $set['unique_code'] = "";
        $set['name'] = "(复制)" . $set['name'];
        $set['create_time'] = time();

        $result = MecSetService::getInstance()->insert($set);
        if ($result) {
            $this->success('复制成功!', '');
        }else {
            $this->error('复制失败，请重新再试!');
        }
    }

    /**
     * 数据写入
     */
    protected function doInsertAction($data) {
        $data['unique_code'] = strtoupper($data['unique_code']);

        if (empty($data['id'])) {
            if (!$this->filterSetCode($data['unique_code'])) {
                return false;
            }

            $data['item_ids'] = serialize(array());
            $data['sort'] = MecSetService::getInstance()->getMaxSort() + 1;
            $data['status'] = 1;
            $data['create_time'] = time();
            $result = MecSetService::getInstance()->insert($data);
        } else {
            $id = intval($data['id']);
            if (isset($data['items'])) {
                $data['item_ids'] = serialize($data['items']);
                unset($data['items']);
            }
            if($data['set_type']){
                $data['set_type'] = implode(',',$data['set_type']);
            }
            $result = MecSetService::getInstance()->update($data, $id);
        }

        return $result;
    }

    /**
     * 列表数据处理
     */
    protected function _index_data_filter(&$data) {
        $size = count($data);

        $mecList = MecService::getInstance()->listMec();
        for ($i=0; $i<$size; $i++) {
            $data[$i]['mec_name'] = $mecList[$data[$i]['mec_id']];

            $itemIDs = unserialize($data[$i]['item_ids']);
            $data[$i]['item_num'] = count($itemIDs);
        }

        $this->assign('mec_list', $mecList);
    }

    /**
     * 体检套餐编号唯一性检查
     *
     * @param $uniqueCode
     * @return boolean
     */
    private function filterSetCode($uniqueCode) {
        if (!$uniqueCode) {
            return false;
        }

        $record = MecSetService::getInstance()->single(array('unique_code'=>$uniqueCode));
        if ($record) {
            return false;
        }

        return true;
    }
}

